<template>
	<view class="u-page">
		<u-navbar
		:autoBack="true"
		:leftIconColor="tksetting.titlecolor" :bgColor="tksetting.color" :titleStyle="{color:tksetting.titlecolor}" :title="title"  :placeholder="true">
		</u-navbar>
		
				<!-- 注意，如果需要兼容微信小程序，最好通过setRules方法设置rules规则 -->
				<u--form
					labelPosition="left"
					:model="model1"
					labelWidth	="90"
					:labelStyle="labelStyle"
					ref="form1"
				>

					<u-form-item
						label="昵称"
						prop="userInfo.name"
						borderBottom
						ref="item1"
						required
					>
					<u--input
						v-model="model1.userInfo.name"
						border="none"
						placeholder="昵称"
						
					>
					</u--input>
					</u-form-item>
					
				    <u-form-item
				    	label="头像"
				    	prop="userInfo.pic"
				    	borderBottom
				    	ref="item1"
				    	required
				    >
				    	<u-upload
				    	    :fileList="fileList1"
				    	    @afterRead="afterRead"
				    	    @delete="deletePic"
				    	    name="1"
				    	    :maxCount="1"
				    	  ></u-upload>
				    </u-form-item>
					
					<u-form-item
						label="性别"
						prop="userInfo.sex"
						borderBottom
						@click="showSex = true; hideKeyboard()"
						ref="item1"
					>
					<u--input
							v-model="model1.userInfo.sex"
							disabled
							disabledColor="#ffffff"
							placeholder="请选择性别"
							border="none"
					></u--input>
					<u-icon
							slot="right"
							name="arrow-right"
					></u-icon>
					</u-form-item>
					
					<u-form-item
						label="血型"
						prop="userInfo.xue"
						borderBottom
						@click="showXue = true; hideKeyboard()"
						ref="item1"
					>
					<u--input
							v-model="model1.userInfo.xue"
							disabled
							disabledColor="#ffffff"
							placeholder="请选择血型"
							border="none"
					></u--input>
					<u-icon
							slot="right"
							name="arrow-right"
					></u-icon>
					</u-form-item>
					
					<u-form-item
						label="出生年月"
						prop="userInfo.birthday"
						borderBottom
						@click="showsr = true; hideKeyboard()"
						ref="item1"
					>
					<u--input
							v-model="model1.userInfo.birthday"
							disabled
							disabledColor="#ffffff"
							placeholder="请选择出生年月"
							border="none"
					></u--input>
					<u-icon
							slot="right"
							name="arrow-right"
					></u-icon>
					</u-form-item>
					
					
					<u-form-item
						label="献血证号"
						borderBottom
						ref="item1"
					>
						<u--input
							v-model="model1.userInfo.xfz"
							border="none"
							placeholder="若有献血请输入献血证号"
						></u--input>
					</u-form-item>
					
				</u--form>
				
				<u-button
					type="primary"
					text="更新"
					customStyle="margin-top: 50px"
					:color="tksetting.color"
					@click="submit"
				></u-button>
				
				<u-action-sheet
					:show="showSex"
					:actions="actions"
					title="请选择性别"
					
					@close="showSex = false"
					@select="sexSelect"
				>
				</u-action-sheet>
				
				
				<u-action-sheet
					:show="showXue"
					:actions="xue_actions"
					title="请选择血型"
					
					@close="showXue = false"
					@select="xueSelect"
				>
				</u-action-sheet>
				  <u-datetime-picker
						ref="datetimePicker"
						:show="showsr"
						v-model="value1"
						mode="date"
						minDate="1752043996"
						:formatter="formatter"
						@confirm="confirmtime"
						@cancel="showsr=false"
				  ></u-datetime-picker>
		
	</view>
</template>

<script>
import {toast,wxcode,clearStorageSync, setStorageSync, getStorageSync, useRouter} from '@/utils/utils.js'
import { mapState } from 'vuex';
import BASE_URL from '@/api/env.js' //引入接口共用地址
	export default {
		data() {
			return {
				value1: Number(new Date()),
				showsr:false,
				showSex:false,
				showXue:false,
				title:'个人信息',
				
				labelStyle:{"font-weight":600},
				fileList1: [],
				fileList2:[],
				disabled1: false,
				actions: [{
							name: '男',
							},
							{
								name: '女',
							}
						],
				xue_actions: [{
							name: 'A',
							},
							{
								name: 'B',
							},
							{
								name: 'O',
							},
							{
								name: 'AB',
							},
							{
								name: '特殊血型',
							}
						],		
				xieyi:0,
				tips: '',
				value: '',
				showCalendar: false,
				showBirthday: false,
				session_ke:'',
				areaname:'',
				time_show:'',
				model1: {
					    userInfo: {
						name: '',
						sex:'',
						xue:'',
						pic:'',
						birthday:'',
						xfz:'',
						renwu:''
					},
			
				},
				
				showarea:false,
				birthday: Number(new Date()),
				arealist: [],
				rules: {
					'userInfo.name': {
						type: 'string',
						required: true,
						message: '请填写昵称',
						trigger: ['blur', 'change']
					},
					'userInfo.sex': {
						type: 'string',
						required: true,
						message: '请选择性别',
						trigger: ['blur', 'change']
					},
					'userInfo.birthday': {
						type: 'string',
						required: true,
						message: '请选择出生年月',
						trigger: ['blur', 'change']
					},
					'userInfo.xue': {
						type: 'string',
						required: true,
						message: '请选择血型',
						trigger: ['blur', 'change']
					},
					
					'userInfo.pic': {
						type: 'string',
						required: true,
						message: '请上传头像',
						trigger: ['blur']
					}
				},
			}
		},
		onLoad() {
			this.init();
		},
		computed:{
			...mapState(['tksetting'])
		},
		onReady() {
			// 如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则
			this.$refs.form1.setRules(this.rules)
			this.$refs.datetimePicker.setFormatter(this.formatter)
		},
		methods: {
			  formatter(type, value) {
				 if (type === 'year') {
					 return `${value}年`
				 }
				 if (type === 'month') {
					 return `${value}月`
				 }
				 if (type === 'day') {
					 return `${value}日`
				 }
				 return value
			},
		    confirmtime(e){
				const date = new Date(e.value);
				const year = date.getFullYear();           // 1990
				const month = String(date.getMonth() + 1).padStart(2, '0'); // 12（注意：getMonth() 返回 0~11）
				const day = String(date.getDate()).padStart(2, '0');        // 12
				this.model1.userInfo.birthday=`${year}-${month}-${day}`;
				this.showsr=false;
				
			},
			async init(){
				this.$api.baseInfo().then(res => {
					//console.log(res)
					//this.model1.userInfo.name=res.data.name;
					
					const result = {};
					for (const key in this.model1.userInfo) {
					  if (res.data.hasOwnProperty(key)) {
					    result[key] = res.data[key];
					  }
					}
					this.model1.userInfo=result;
					this.fileList1.push({"url":res.data.pic})
					
				})
			},
			async getarealist(){
				const res=await this.$api.arealist({t1:'label',t2:'id',all:''});
				if (res.code == 0) {
					this.arealist=[res.data];
					this.showarea=true;
				}
			},
			routs(id){
				useRouter('/pages/public/page',{id:id},'navigateTo')
			},
			navigateBack() {
				uni.navigateBack()
			},
			sexSelect(e) {
				this.model1.userInfo.sex = e.name
				this.$refs.form1.validateField('userInfo.sex')
			},
			xueSelect(e) {
				this.model1.userInfo.xue = e.name
				this.$refs.form1.validateField('userInfo.xue')
			},
			change(e) {
				// console.log(e);
			},
		
			async submit() {
				// 如果有错误，会在catch中返回报错信息数组，校验通过则在then中返回true
				const _this=this;
				console.log(this.model1.userInfo)
				try{
					this.model1.userInfo.pic=this.fileList1[0].url;
					//this.model1.userInfo.xd_pic=this.fileList2[0].url;	
				}catch(e){}
				
				const yz=await  _this.$refs.form1.validate().then(res => {
					return true;
				}).catch(errors => {
					uni.$u.toast('请将注册信息输入完整');
					return false
				})
				if(yz){
					_this.model1.userInfo.renwu=1;
					const ress= await  _this.$api.baseInfoSave(_this.model1.userInfo);
					console.log(ress)
					if(ress.code==0){
						uni.$u.toast(ress.msg)
						uni.navigateBack();
					}else{
						uni.$u.toast(ress.msg)
					}
				}	
				
			},
			hideKeyboard() {
				uni.hideKeyboard()
			},
			
			confirm(e) {
			    this.areaname=e.value[0].label;
				this.model1.userInfo.area=e.value[0].id;
				this.showarea=false;
			},
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1);
				this.model1.userInfo.pic='';
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file);
				let fileListLen = this[`fileList${event.name}`].length;
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: "uploading",
						message: "上传中",
					});
				});
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url);
					let item = this[`fileList${event.name}`][fileListLen];
					this[`fileList${event.name}`].splice(
						fileListLen,
						1,
						Object.assign(item, {
							status: "success",
							message: "",
							url: result,
						})
					);
					fileListLen++;
				}
			},
			uploadFilePromise(url) {
				let _this=this;
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url:BASE_URL + '/upload/upimg', // 仅为示例，非真实的接口地址
						filePath: url,
						name: "file",
						header:{
							token:getStorageSync('token')
						},
						success: (res) => {
							console.log(res)
							let shopewm=JSON.parse(res.data).data;
							resolve(shopewm)
						},
					});
				});
			},
		},
	}
</script>

<style lang="scss">
	
.u-page{
	padding: 40rpx;
}

</style>
